import React, { useState } from 'react';
import { useStudents } from './StudentContext';
import SearchForm from '../../components/SearchForm/SearchForm';
import StudentTable from '../../components/StudentTable/StudentTable';
import StudentModal from '../../components/StudentModal/StudentModal';
import DeleteConfirm from '../../components/DeleteConfirm/DeleteConfirm';
import { IStudent } from '../../types';
import styles from './StudentsPage.module.css';

const StudentsPage: React.FC = () => {
  const { filteredStudents, addStudent, updateStudent, deleteStudent, setFilters } = useStudents();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [currentStudent, setCurrentStudent] = useState<IStudent | null>(null);
  const [studentToDelete, setStudentToDelete] = useState<{ id: string; name: string } | null>(null);

  const handleSearch = (filters: { name: string; gender: string; studentId: string }) => {
    setFilters(filters);
  };

  const handleAdd = () => {
    setCurrentStudent(null);
    setIsModalOpen(true);
  };

  const handleEdit = (student: IStudent) => {
    setCurrentStudent(student);
    setIsModalOpen(true);
  };

  const handleDelete = (id: string) => {
    const student = filteredStudents.find(s => s.id === id);
    if (student) {
      setStudentToDelete({ id, name: student.name });
      setIsDeleteModalOpen(true);
    }
  };

  const confirmDelete = () => {
    if (studentToDelete) {
      deleteStudent(studentToDelete.id);
      setStudentToDelete(null);
    }
  };

  const handleSubmit = (student: Omit<IStudent, 'id'> | { id: string } & Partial<IStudent>) => {
    if ('id' in student) {
      // 编辑模式
      updateStudent(student.id, student);
    } else {
      // 新增模式
      addStudent(student);
    }
  };

  return (
    <div className={styles.studentsPage}>
      <h2 className={styles.pageTitle}>学生管理</h2>
      <SearchForm onSearch={handleSearch} />
      <StudentTable 
        students={filteredStudents} 
        onEdit={handleEdit} 
        onDelete={handleDelete} 
        onAdd={handleAdd} 
      />
      
      <StudentModal 
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSubmit={handleSubmit}
        student={currentStudent}
      />
      
      <DeleteConfirm 
        isOpen={isDeleteModalOpen}
        onClose={() => setIsDeleteModalOpen(false)}
        onConfirm={confirmDelete}
        studentName={studentToDelete?.name || ''}
      />
    </div>
  );
};

export default StudentsPage;